#!/usr/bin/python3
"""
Configure the WALinuxAgent.

The tree must already include /etc/waagent.conf, and it is modified
in place. Every attempt is made to preserve the structure of the file,
though comments are completely ignored.
"""

import fileinput
import sys

import osbuild.api


SCHEMA = """
"additionalProperties": false,
"required": ["config"],
"properties": {
  "config": {
    "additionalProperties": false,
    "description": "WALinuxAgent config options",
    "type": "object",
    "properties": {
      "ResourceDisk.Format": {
        "description": "Enable or disable disk formatting.",
        "type": "boolean"
      },
      "ResourceDisk.EnableSwap": {
        "description": "Enable or disable swap.",
        "type": "boolean"
      }
    }
  }
}
"""


def bool_to_y_n(b):
    if b:
        return "y"
    return "n"


def main(tree, options):
    sshd_config = options.get("config", {})
    resource_disk_format = sshd_config.get("ResourceDisk.Format")
    resource_disk_enable_swap = sshd_config.get("ResourceDisk.EnableSwap")
    changes = {}
    if resource_disk_format is not None:
        changes["resourcedisk.format"] = {
            "key": "ResourceDisk.Format",
            "value": bool_to_y_n(resource_disk_format)
        }
    if resource_disk_enable_swap is not None:
        changes["resourcedisk.enableswap"] = {
            "key": "ResourceDisk.EnableSwap",
            "value": bool_to_y_n(resource_disk_enable_swap)
        }

    # For each of the configured options, find the first non-commented out instance
    # of the option and replace it (if necessary). If it does not already exist, append
    # the option to the end of the file.
    # Keys are case insensitive, values are not. Try to preserve the key and default to
    # camel-case.
    with fileinput.input(files=(f"{tree}/etc/waagent.conf"), inplace=True) as f:
        for line in f:
            line_list = line.split(sep='=')
            if len(line_list) == 2:
                key, current_value = line_list
                entry = changes.pop(key.lower(), None)
                if entry is not None and current_value != entry['value']:
                    sys.stdout.write(f"{key}={entry['value']}\n")
                    continue
            sys.stdout.write(line)
    with open(f"{tree}/etc/waagent.conf", mode="a") as f:
        for entry in changes.values():
            f.write(f"{entry['key']}={entry['value']}\n")

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
